import { mapState } from "vuex";
import { parseTime } from "@/utils/zhongkeruan";
import { getConstForCurTaskOperateBtnConfig } from "@/utils/dict/cfg";
import { isString } from '@/utils/validate'

export default {
  data() {
    return {
      // 表单内置参数
      myFormData: {},
      // 办理关联表单操作按钮控制
      curTaskOperateBtnConfig: getConstForCurTaskOperateBtnConfig()
    }
  },
  computed: {
    ...mapState(["selfForm", "user"]),
  },
  created() {
    this.myFormData = this.$store.state.selfForm.initFormData;
    console.log('CptSelfForm myFormData', this.myFormData)
  },
  mounted() {
    this.initCurTaskOperateBtnConfig()
  },
  methods: {
    onSubmitForm() {
      this.$refs["SelfFormRender"]
        .getFormData()
        .then((formData) => {
          // 内部表单校验
          if (this.$refs["SelfFormRender"]._curSelfFormValidate) {
            let selfValidateResult = this.$refs["SelfFormRender"]._curSelfFormValidate()
            if (selfValidateResult && !selfValidateResult.isValidate) {
              console.error('selfValidateResult msg: ', selfValidateResult.msg)
              reject(selfValidateResult.msg)
              return
            }
          }
          // Form Validation OK
          console.log("Form Validation OK", formData);
          const params = {
            formData: this.formConfCopy,
            valData: {
              ...this.getFormApplyInfo(),
              ...this.befCompleteFormDataFilter(formData)
            },
            taskForm: {
              ...this.taskForm
            }
          };
          this.$emit("submit", params);
        })
        .catch((error) => {
          // Form Validation failed
          console.log("Form Validation failed", error);
        });
    },
    onResetForm() {
      this.$refs["SelfFormRender"].resetForm();
    },
    onSaveForm() {
      let formData = this.$refs["SelfFormRender"].getFormData(false)
      const params = {
        formData: this.formConfCopy,
        valData: {
          ...this.getFormApplyInfo(),
          ...this.befCompleteFormDataFilter(formData)
        },
        taskForm: {
          ...this.taskForm
        }
      };
      this.$emit("save", params);
    },
    onCancelForm() {
      this.$emit("cancel", {});
    },
    getFormDataPromise(params) {
      return new Promise((resolve, reject) => {
        this.$refs["SelfFormRender"]
        .getFormData()
        .then((formData) => {
          // 内部表单校验
          if (this.$refs["SelfFormRender"]._curSelfFormValidate) {
            let selfValidateResult = this.$refs["SelfFormRender"]._curSelfFormValidate(params)
            if (selfValidateResult && !selfValidateResult.isValidate) {
              console.error('selfValidateResult msg: ', selfValidateResult.msg)
              reject(selfValidateResult.msg)
              return
            }
          }
          // Form Validation OK
          resolve(this.befCompleteFormDataFilter(formData))
        })
        .catch((error) => {
          // Form Validation failed
          console.log("Form Validation failed", error);
          reject(error)
        });
      });
    },
    getFormData() {
      let formData = this.$refs["SelfFormRender"].getFormData(false)
      return this.befCompleteFormDataFilter(formData)
    },
    getAllFormData() {
      return { ...this.$refs["SelfFormRender"].getFormData(false) }
    },
    getFormApplyInfo() {
      let myFormData = this.$store.state.selfForm.initFormData;
      if (!myFormData) {
        myFormData = {}
      }

      let user = this.$store.state.user.userInfo;
      if (!user) {
        user = {}
      }
      // 大类/子类/编号/申请人/申请部门/申请时间/
      let applyInfo = {
        'cur_formTitle': `${myFormData.cur_subcategory || ''} 申请`,
        'cur_category': myFormData.cur_category || '',
        'cur_subcategory': myFormData.cur_subcategory || '',
        'cur_businessKey': myFormData.cur_businessKey || '',
        'cur_userNickName': user.nickName || '',
        'cur_userDeptName': user.dept.deptName || '',
        'cur_applyDateTime': parseTime(Date.now()) || '',
      }
      console.log('getFormApplyInfo applyInfo', applyInfo)
      return applyInfo
    },
    /**
     * 操作按钮权限控制
     */
    initCurTaskOperateBtnConfig() {
      if (this.$refs["SelfFormRender"]) {
        let formDefaultData = this.$refs["SelfFormRender"].getFormData(false)
        console.log('initCurTaskOperateBtnConfig -> formDefaultData', formDefaultData)
        if (formDefaultData) {
          for (const key in this.curTaskOperateBtnConfig) {
            this.curTaskOperateBtnConfig[key] = ((formDefaultData[key] === undefined) || (formDefaultData[key] === false)) ? false : (
              (typeof formDefaultData[key] === 'boolean') ? true : formDefaultData[key]
            )
          }
        }
        console.log('initCurTaskOperateBtnConfig -> curTaskOperateBtnConfig:', this.curTaskOperateBtnConfig)
        // 隐藏流程操作配置表单
        this.$refs["SelfFormRender"].hideWidgets('curTaskOperateBtnConfig');
      }
    },
    getCurTaskOperateBtnConfig() {
      this.initCurTaskOperateBtnConfig()
      return JSON.parse(JSON.stringify(this.curTaskOperateBtnConfig))
    },
    befCompleteFormDataFilter(fData) {
      let newFdata = {}
      if (fData) {
        for (const key in fData) {
          if (!(Object.keys(this.curTaskOperateBtnConfig).some(v => { return v === key }))) {
            newFdata[key] = fData[key]
          }
        }
      }
      console.log('befCompleteFormDataFilter newFdata: ', newFdata)
      return newFdata
    },
    _initInnerFormData(formData) {
      setTimeout(() => {
        this.$nextTick(() => {
          let selfFormRenderRef =  this.$refs["SelfFormRender"];
          if (selfFormRenderRef) {
            let fData = formData || {}
            for (const key in fData) {
              switch (key) {
                case 'cur_formTitle':
                case 'cur_category':
                case 'cur_subcategory':
                case 'cur_businessKey':
                case 'cur_userNickName':
                case 'cur_userDeptName':
                case 'cur_applyDateTime':
                  let widgetRef = selfFormRenderRef.getWidgetRef(key)
                  if (widgetRef) {
                    widgetRef.setWidgetOption('textContent', fData[key])
                  }
                  break;
                default:
                  break;
              }
            }
          }
        })
      }, 1000);
    },
    setDataCfg(dataCfg) {
      let temp = {}
      if (dataCfg) {
        if (dataCfg.formContent) {
          temp.formContent = isString(dataCfg.formContent) ? JSON.parse(dataCfg.formContent) : dataCfg.formContent
        }
        temp.formData = dataCfg.formData ? dataCfg.formData : null
      }
      if (this.$refs['SelfFormRender']) {
        if (temp.formContent) {
          this.$refs['SelfFormRender'].setFormJson(temp.formContent)
        }
        if (temp.formData) {
          this.$refs['SelfFormRender'].setFormData(temp.formData)
        }

        this.$nextTick(() => {
          // 隐藏流程操作配置表单
          this.$refs["SelfFormRender"].hideWidgets('curTaskOperateBtnConfig');
        });
      }
    },
    /**
     * 组件数据传递，便于表单设置系统内部数据
     * @param {*} data 
     * @returns 
     */
    transSelfFormData(data) {
      if (this.$refs['SelfFormRender'] && this.$refs["SelfFormRender"]._curSelfFormTransData) {
        return this.$refs["SelfFormRender"]._curSelfFormTransData(data);
      }
    },
    /**
     * 组件数据传递，便于系统内部监听表单事件
     * @param {*} param 
     */
    onDownloadClick(param) {
      console.log('onDownloadClick', param)
      this.download(param.url, {
        ...param.postParams
      }, param.fileName)
    }
  }
};
